import {
  BrowserWindow,
  BrowserView,
  Menu,
  Tray,
  protocol,
  net,
  dialog,
  app,
  screen,
  ipcMain,
  shell,
  globalShortcut
} from 'electron'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import path, { join } from 'path'
import fs from 'fs'
import url from 'url'
import { exec } from 'child_process'
import { setElectronStore } from '../renderer/src/electronStore/index.js'
// import icon from '../../resources/icon.png?asset'
// import icon from '/@/assets/icons/tray.png'
import icon from '../renderer/src/assets/icons/tray.png'

const loginWidth = 320
const loginHeight = 324
const mainWidth = 900
const mainHeight = 670
const deviationDistance = 50
let initMainPosition = { x: 0, y: 0 }
let isLogged = false
let loginWindow = ''
const windowList = []
const createLoginWindow = () => {
  loginWindow = new BrowserWindow({
    icon,
    // ...(process.platform === 'linux' ? { icon } : {}),
    width: loginWidth,
    height: loginHeight,
    autoHideMenuBar: true,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      enableRemoteModule: true
    },
    resizable: false,
    frame: false,
    titleBarStyle: 'hidden'
  })
  loginWindow.openDevTools()
  loginWindow.on('ready-to-show', () => {
    loginWindow.show()
  })
  loginWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    loginWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    loginWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}
const createNewWindow = (flag = false) => {
  try {
    isLogged = true
    const newWindow = new BrowserWindow({
      icon,
      width: mainWidth,
      height: mainHeight,
      autoHideMenuBar: true,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: true,
        preload: join(__dirname, '../preload/index.js'),
        enableRemoteModule: true
      },
      resizable: false,
      frame: false,
      titleBarStyle: 'hidden'
    })
    newWindow.openDevTools()
    // 每新增一个窗口，将新窗口位置偏移
    if (flag) {
      const { deviationLeft, deviationTop } = setWindowPosition()
      newWindow.setPosition(deviationLeft, deviationTop)
    }
    newWindow.on('ready-to-show', () => {
      newWindow.show()
    })
    newWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      newWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      newWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }
    windowList.push(newWindow)
    console.log(mainWidth, 'mainWidth')
  } catch (error) {
    console.log(error, '创建主窗口报错')
  }
}
// 计算新窗口定位点
const setWindowPosition = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  const deviationCount = BrowserWindow.getAllWindows().length - 1
  const deviationLeft = (width - mainWidth) / 2 + deviationDistance * deviationCount
  const deviationTop = (height - mainHeight) / 2 + deviationDistance * deviationCount
  return { deviationLeft, deviationTop }
}
// 创建托盘
const createDockTray = () => {
  const tray = new Tray(path.join(__dirname, '../../src/renderer/src/assets/icons/tray.png'))
  //   const tray = new Tray('../renderer/src/assets/icons/tray.png')
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示',
      // type: "normal",
      click: () => {
        if (isLogged) {
          const target = windowList[0]
          // 所有窗口都已关闭则创建一个主窗口
          target ? target.show() : createNewWindow()
        } else {
          loginWindow.show()
        }
      }
    },
    {
      label: '最小化',
      click: () => {
        const browserList = BrowserWindow.getAllWindows()
        browserList.forEach((item) => {
          item.minimize()
        })
      }
    },
    {
      label: '退出',
      click: () => {
        app.quit()
      }
    }
  ])
  tray.setToolTip('这是一个托盘')
  tray.setContextMenu(contextMenu)
}
// 注册全局快捷键
const createGlobalShortcut = () => {
  commandList.forEach((item) => {
    const { command, callback } = item
    globalShortcut.register(command, () => {
      if (!isLogged) {
        // 未登录禁止调用快捷键的回调
        return
      }
      callback()
    })
  })
}
// 关闭当前窗口
const closeActiveWindow = () => {
  const focusWindow = BrowserWindow.getFocusedWindow()
  if (focusWindow) {
    focusWindow.close()
  }
}
// 打开读取文件窗口
const openFile = () => {
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
        { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }
      ]
    })
    .then((result) => {
      if (!result.canceled) {
        const focusWindow = BrowserWindow.getFocusedWindow()
        focusWindow.webContents.send('switchToFile')
        const filePath = result.filePaths
        const list = []
        const readFileFun = async (filePath) => {
          for (const path of filePath) {
            const fileContent = await fs.promises.readFile(path)
            const data = fileContent.toString('base64')
            list.push(data)
          }
          focusWindow.webContents.send('openFileMes', list)
        }
        setTimeout(() => {
          readFileFun(filePath)
        }, 500)
      }
    })
}
// 设置嵌套窗口
const createNestingWindow = () => {
  const view = new BrowserView()
  view.setBounds({ x: 410, y: 290, width: 200, height: 200 })
  view.webContents.loadFile(path.join(__dirname, '../../src/renderer/src/html/nesting.html'))
  view.webContents.openDevTools()
  const focusWindow = BrowserWindow.getFocusedWindow()
  focusWindow.setBrowserView(view)
}
// 调用系统键盘;
const openSystemKeyboard = () => {
  // window: win32  mac: darwin  linux: linux
  const commandStr = process.platform === 'win32' ? 'osk.exe' : 'onboard' // onboard是Linux下的命令
  exec(commandStr, (error, stdout, stderr) => {
    if (error) {
      console.log(`打开键盘报错: ${error.message}`)
      return
    }
  })
}
// 自定义协议(其实就是拦截器，类似于axios)
const customProtocol = () => {
  protocol.handle('myapp', (request) => {
    console.log(request.url)
    // <img src="myapp://src/assets/imgs/boy.png" alt=""></img>
    // index.html中图片路径如上，将以“myapp”开头的资源进行拦截，并将“myapp://”替换为空
    const filePath = request.url.replace('myapp://', '')
    const p = path.join(__dirname, filePath)
    const l = url.pathToFileURL(p).toString()
    console.log(l, 'l')
    return net.fetch(l)
  })
}
protocol.registerSchemesAsPrivileged([
  { scheme: 'myapp', privileges: { secure: true, standard: true, supportFetchAPI: true } }
])
app.whenReady().then(() => {
  try {
    console.log('1----')
    electronApp.setAppUserModelId('com.electron')
    console.log('2----')
    app.on('browser-window-created', (_, window) => {
      optimizer.watchWindowShortcuts(window)
    })
    console.log('3----')
    customProtocol()
    console.log('4----')
    createLoginWindow()
    console.log('5----')
    createDockTray()
    console.log('6----')
    createGlobalShortcut()
    console.log('7----')
    app.on('activate', function () {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (BrowserWindow.getAllWindows().length === 0) createLoginWindow()
    })
    console.log('8----')
    // 登录后关闭登录窗口 新建主窗口
    ipcMain.on('is-login', (event, arg) => {
      console.log('登录-主窗口')
      loginWindow.close()
      createNewWindow()
    })
    ipcMain.on('toggleFullScreen', (event, arg) => {
      //   ipcMain.handle('toggle-full-screen', (event, arg) => {
      console.log('进入到了-toggle-full-screen')
      const focusWindow = BrowserWindow.getFocusedWindow()
      // const focusWindow = windowList[0]
      const { width, height } = screen.getPrimaryDisplay().workAreaSize
      const { x, y, width: w, height: h } = focusWindow.getBounds()
      if (w === width && h === height) {
        focusWindow.setBounds({
          x: initMainPosition.x,
          y: initMainPosition.y,
          width: mainWidth,
          height: mainHeight
        })
      } else {
        initMainPosition = { x, y }
        focusWindow.setBounds({ x: 0, y: 0, width, height })
      }
    })
  } catch (error) {
    console.log(error, 'ready-error')
    const focusWindow = windowList[1]
    focusWindow.webContents.send('sendError', { flag: 'heihei', error })
  }

  // 窗口最小化
  ipcMain.on('window-minimize', (event, arg) => {
    if (arg) {
      const focusWindow = BrowserWindow.getFocusedWindow()
      focusWindow.minimize()
    } else {
      loginWindow.minimize()
    }
  })
  // 关闭窗口从任务栏中移除
  ipcMain.on('window-close', (event, arg) => {
    const focusWindow = BrowserWindow.getFocusedWindow()
    const target = windowList.find((item) => item.id === focusWindow.id)
    if (isLogged) {
      target.close()
      windowList.splice(windowList.indexOf(target), 1) // 移除掉当前关闭的窗口
    } else {
      loginWindow.hide()
    }
  })
  // 窗口拖动时,当前窗口是active窗口，直接修改其位置
  ipcMain.on('drag-render', (event, arg) => {
    const { offsetX, offsetY } = arg
    const focusWindow = BrowserWindow.getFocusedWindow()
    const position = focusWindow.getPosition()
    focusWindow.setPosition(position[0] + offsetX, position[1] + offsetY, true)
  })
  // 切换全屏或还原
  app.on('toggle-full-screen', (event, arg) => {
    console.log('app监听到点击')
  })
  //   ipcMain.on('toggle-full-screen', (event, arg) => {

  // 监听菜单栏点击
  ipcMain.on('click-menu', (event, arg) => {
    const target = commandList.find((item) => item.command === arg)
    if (target) {
      const { callback } = target
      callback()
    }
  })
  ipcMain.on('create-nest-window', (event, arg) => {
    createNestingWindow()
  })
  ipcMain.on('is-main-window', (event, arg) => {
    if (!isLogged) {
      loginWindow.close()
      createNewWindow()
    }
  })
})

const commandList = [
  {
    command: 'Ctrl+Shift+N',
    callback: () => {
      createNewWindow(true)
    }
  },
  {
    command: 'Ctrl+Shift+W',
    callback: () => {
      closeActiveWindow()
    }
  },
  {
    command: 'Ctrl+O',
    callback: () => {
      openFile()
    }
  },
  {
    command: 'Ctrl+S+K',
    callback: () => {
      openSystemKeyboard()
    }
  }
]
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
